<template>
  <div>
    <div id="edit"></div>
  </div>
</template>

<script setup name="editor">
  import "froala-editor/css/froala_editor.pkgd.min.css";
  import "froala-editor/css/froala_style.min.css";
  import "froala-editor/js/languages/zh_cn.js";
  import "froala-editor/js/plugins.pkgd.min.js";
  import FroalaEditor from "froala-editor/js/froala_editor.pkgd.min.js";
  import { useStore } from "@/hooks/store/useStore"
  import { isEmpty } from "@/utils/validate"

  const { base } = useStore()

  const props = defineProps({
    content: {
      type: String,
      default: null,
    }
  });

  const data = ref('')
  const editor = ref()

  // 创建编辑器方法
  const initFroala = () => {
    editor.value = new FroalaEditor("#edit", {
      placeholderText: '请输入内容...',
      language: 'zh_cn', //中文
      width: 950,
      heightMin: 300,
      heightMax: 800,
      charCounterCount: false, //是否显示字数
      colorsHEXInput: false, //关闭16进制色值
      toolbarSticky: false, //操作栏是否自动吸顶
      fontSize: ['8', '9', '10', '11', '12', '13', '14', '15', '16', '18', '24', '30', '36', '48'],
      quickInsertButtons: ['image', 'table', 'ul', 'ol', 'hr'], //快速插入项
      secondtoolbar: false,
      allowedImageTypes: ['jpeg', 'jpg', 'png', 'gif'],
      imageMove: true, //图片是否能拖动
      imageDefaultDisplay: 'inline', //图片为行级元素
      imageUploadURL: $http.adornUrl('/file/editor_picture'), //图片上传地址
      fileUploadURL: $http.adornUrl('/file/editor_file'), //上传url
      requestHeaders: {
        Authorization: 'Bearer ' + base.token,
      },
      events: {
        initialized: function ()  {
          editor.value.html.set(props.content)

          // 隐藏底部Powered by
          this.$second_tb.html("")
        },
        'contentChanged': function () {
          data.value = this.html.get()
        },
        input: function (inputEvent) {
          data.value = this.html.get()
        },
        keypress: function (inputEvent) {
          data.value = this.html.get()
        },
        'paste.after': function () {
          data.value = this.html.get()
        },
        'window.cut': function () {
          // data.value = this.html.get()
        }
      },
    });
  }


  // 初始化内容
  watch(() => props.content, (value, oldValue) => {
    if((editor.value instanceof Object) && !isEmpty(editor.value.html)) {
      editor.value.html.set(value);

      data.value = value
    }
  })


  // 使用defineExpose暴露content
  defineExpose({
    data
  });


  // 初始化编辑器
  onMounted(() => {
    initFroala();
  })

</script>
